package day15.udpsocket02;

import java.io.*;
import java.net.Socket;
import java.util.UUID;

/**
 * @author Xiao
 * @date 2021/8/10
 */
public class ServerThread implements Runnable{
    private Socket so;

    public ServerThread(Socket so) {
        this.so = so;
    }

    @Override
    public void run() {
        BufferedOutputStream bos = null;
        try {
            //从客户端读入文件到服务器，再从服务器写出文件到本地文件夹
            BufferedInputStream bis = new BufferedInputStream(so.getInputStream());
             bos = new BufferedOutputStream(new FileOutputStream(
                    "classpractice\\src\\day15\\udpsocket02\\"
                            + UUID.randomUUID().toString().replace(
                            "-","") + ".txt"));
            int b;
            while ((b = bis.read()) != -1) {
                bos.write(b);
            }
            System.out.println("服务器上传文件。。。");

            so.shutdownInput();
            //将反馈信息写出给客户端
            OutputStream os = so.getOutputStream();
            os.write("文件上传完成。。。\r\nOver。。。".getBytes());

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (so != null) {
                try {
                    so.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
